package coupon_logic

import (
	"context"
	"errors"
	"fmt"
	"wx-uniapp-go/internal/repository/dto"
	"wx-uniapp-go/internal/repository/models"
)

type CouponLogic struct {
	Ctx context.Context
}

func NewCouponLogic(ctx context.Context) *CouponLogic {
	return &CouponLogic{Ctx: ctx}
}

// CreateCouponRule 创建优惠券规则
func (l *CouponLogic) CreateCouponRule(req *dto.CreateCouponRuleReq) error {
	// 检查类型是否有效
	if req.Type != models.CouponTypeAmount && req.Type != models.CouponTypeDiscount {
		return errors.New("无效的优惠券类型")
	}

	// 检查商品类型是否有效
	if req.ProductType == "" {
		req.ProductType = models.ProductTypeAll
	} else if req.ProductType != models.ProductTypeAll && req.ProductType != models.ProductTypeVip {
		return errors.New("无效的商品类型")
	}

	rule := &models.CouponRule{
		Name:        req.Name,
		Type:        req.Type,
		Value:       req.Value,
		MinAmount:   req.MinAmount,
		ValidDays:   req.ValidDays,
		DayLimit:    req.DayLimit,
		TotalLimit:  req.TotalLimit,
		ProductType: req.ProductType,
		Status:      1, // 默认启用
		Description: req.Description,
	}

	_, err := models.Insert(l.Ctx, rule)
	return err
}

// UpdateCouponRule 更新优惠券规则
func (l *CouponLogic) UpdateCouponRule(req *dto.UpdateCouponRuleReq) error {
	rule := new(models.CouponRule)
	exists, err := models.Get(l.Ctx, rule, "id = ?", req.Id)
	if err != nil {
		return err
	}
	if !exists {
		return errors.New("规则不存在")
	}

	if req.Name != "" {
		rule.Name = req.Name
	}
	if req.Value > 0 {
		rule.Value = req.Value
	}
	if req.MinAmount >= 0 {
		rule.MinAmount = req.MinAmount
	}
	if req.ValidDays > 0 {
		rule.ValidDays = req.ValidDays
	}
	if req.DayLimit >= 0 {
		rule.DayLimit = req.DayLimit
	}
	if req.TotalLimit >= 0 {
		rule.TotalLimit = req.TotalLimit
	}
	if req.ProductType != "" {
		if req.ProductType != models.ProductTypeAll && req.ProductType != models.ProductTypeVip {
			return errors.New("无效的商品类型")
		}
		rule.ProductType = req.ProductType
	}
	if req.Status > 0 {
		rule.Status = req.Status
	}
	if req.Description != "" {
		rule.Description = req.Description
	}

	return models.Update(l.Ctx, fmt.Sprintf("id = %d", req.Id), rule)
}

// DeleteCouponRule 删除优惠券规则
func (l *CouponLogic) DeleteCouponRule(id int64) error {
	// 检查是否存在
	exists, err := models.Exists(l.Ctx, &models.CouponRule{}, "id = ?", id)
	if err != nil {
		return err
	}
	if !exists {
		return errors.New("规则不存在")
	}

	// 检查是否有关联的优惠券
	exists, err = models.Exists(l.Ctx, &models.UserCoupon{}, "rule_id = ?", id)
	if err != nil {
		return err
	}
	if exists {
		return errors.New("规则已被使用，不能删除")
	}

	return models.Delete(l.Ctx, &models.CouponRule{Id: id}, "")
}

// ListCouponRules 查询优惠券规则列表
func (l *CouponLogic) ListCouponRules(req *dto.ListCouponRuleReq) (*dto.ListCouponRuleResp, error) {
	where := "1=1"
	var params []interface{}

	if req.Type != "" {
		where += " AND type = ?"
		params = append(params, req.Type)
	}
	if req.ProductType != "" {
		where += " AND product_type = ?"
		params = append(params, req.ProductType)
	}
	if req.Status > 0 {
		where += " AND status = ?"
		params = append(params, req.Status)
	}

	// 获取总数
	total, err := models.Count(l.Ctx, &models.CouponRule{}, where, params...)
	if err != nil {
		return nil, err
	}

	// 获取列表
	var rules []*models.CouponRule
	_, err = models.FindByPage(l.Ctx, &rules, req.Page, req.Size, where, params...)
	if err != nil {
		return nil, err
	}

	// 转换响应
	list := make([]*dto.CouponRuleResp, len(rules))
	for i, rule := range rules {
		list[i] = &dto.CouponRuleResp{
			Id:          rule.Id,
			Name:        rule.Name,
			Type:        rule.Type,
			Value:       rule.Value,
			MinAmount:   rule.MinAmount,
			ValidDays:   rule.ValidDays,
			DayLimit:    rule.DayLimit,
			TotalLimit:  rule.TotalLimit,
			ProductType: rule.ProductType,
			Status:      rule.Status,
			Description: rule.Description,
		}
	}

	return &dto.ListCouponRuleResp{
		Total: total,
		List:  list,
	}, nil
}
